package com.jet.rtdb.socket.client.netty;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jet.rtdb.common.utils.MessageConstant;
import com.jet.rtdb.pojo.QueryLastDataList;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.Charset;

/**
 * @Author: zhangkaifeng.
 * @CreateTime: 2017/8/18 10:25
 * @Description:
 */


public class MessageClientEncoder extends MessageToByteEncoder<Object> {


    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        GsonBuilder gsonbuilder = new GsonBuilder().serializeNulls();
        Gson gson = gsonbuilder.create();
        try {
            if (o instanceof QueryLastDataList) {
                String string = gson.toJson(o);
                byte[] bytes = string.getBytes(Charset.forName("utf-8"));
                byteBuf.writeByte(MessageConstant.GET_POINT_LAST_DATA);
                byteBuf.writeInt(bytes.length);
                byteBuf.writeBytes(bytes);
                channelHandlerContext.writeAndFlush(byteBuf);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            byteBuf.release();
        }
    }
}
